#ifndef SERIAL_H
#define SERIAL_H

#include <QSerialPort>
#include <QByteArray>
#include <QTimer>
#include <QStringList>
#include <QMutex>

class Serial : public QObject
{
    Q_OBJECT

public:
    explicit Serial(QObject *parent = nullptr);
    ~Serial();

    QStringList availablePorts();
    bool open(const QString &portName);
    bool isOpen();
    void close();
    bool send(char byte);
    bool send(const QByteArray &data);

    QString connectingPort();
    bool waitForRx(int msecs=1000);

    virtual bool checkRxData(const QByteArray &frame) const
    {
        Q_UNUSED(frame);
        return true;
    }

signals:
    void connectionChanged(bool connected);
    void frameIn(const QByteArray &frame);
    void pkgIn(const QByteArray &data);

protected:
    bool blockingRecv = false;
    QSerialPort *serialport;
    QTimer frameTimer;
    QByteArray rxBuf;
    int rxMaxSize = 1024;

    void onFrameEnd();
    void onReplyTimeout();

private slots:
    void onReadyRead();

protected:
    void onError(QSerialPort::SerialPortError error);
};

#endif // SERIAL_H
